package com.laicunba.service.impl;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.laicunba.dao.GenericQueryDao;
import com.laicunba.pojo.TemplateDO;
import com.laicunba.service.TemplateService;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.StringUtil;

@Service
public class TemplateServiceImpl extends BaseServiceImpl implements TemplateService {
	private static final Logger LOG = Logger.getLogger(TemplateServiceImpl.class);
	private Properties defaultProperties = null;

	@Autowired
	private GenericQueryDao queryDao;

	@Override
	public TemplateDO findByCodeWidthDefault(String code) {
		loadPropertiesIfNotExist();
		TemplateDO tmp = findByCode(code);
		if (tmp != null) {
			return tmp;
		}
		String tmpContent = defaultProperties.getProperty(code);
		if (StringUtil.isEmpty(tmpContent)) {
			return null;
		}
		tmp = new TemplateDO();
		tmp.setCode(code);
		tmp.setName(code);
		tmp.setType("default");
		tmp.setContent(tmpContent);
		AssertUtil.assertTrue(create(tmp));
		return tmp;
	}

	private void loadPropertiesIfNotExist() {
		if (defaultProperties != null) {
			return;
		}
		defaultProperties = new Properties();
		try {
			defaultProperties.load(new InputStreamReader(TemplateServiceImpl.class.getResourceAsStream("resource/default_template.ini"), "utf-8"));
		} catch (IOException e) {
			LOG.error("加载默认的模版文件出错了!", e);
		}

	}

	@Override
	public TemplateDO findByCode(String code) {
		return queryDao.selectOne("TEMPLATE.findByCode", code);
	}

	@Override
	public String simpleMerge(String templateString, Map<String, Object> map) {
		for (String key : map.keySet()) {
			if (map.get(key) == null) {
				map.put(key, "");
			}
			templateString = templateString.replace(key, map.get(key).toString());
		}
		return templateString;
	}

	@Override
	public List<TemplateDO> findByType(String type) {
		return this.queryDao.selectList("TEMPLATE.findByType", type);
	}

}
